from django.shortcuts import render
from app01 import models
from django import forms
from django.core.validators import ValidationError
# Create your views here.
from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from .pay import AliPay
import uuid
from urllib.parse import parse_qs
from app01.utils.bootstrape import BootStrapForm,BootStrapModelForm
from django.core.exceptions import ValidationError
from app01.utils.encrypt import md5
from app01.utils.code import check_code
from io import BytesIO


# Create your views here.
def index(request):
     return render(request,'index.html')
 
 
def dingdan(request):
    # 实例化AliPay
    alipay = AliPay(
        appid="2021000119681986",
        app_notify_url='http://127.0.0.1:5600/app01/check/',#支付宝会向这个地址发送post请求
        return_url='http://127.0.0.1:5600/app01/show/',#支付宝会向这个地址发送get请求
        app_private_key_path=r'D:\Django-water\water\app01\rsakey\private2048.txt',  # 应用私钥
        alipay_public_key_path=r'D:\Django-water\water\app01\rsakey\paypublic.txt',  # 支付宝公钥
      
        debug=True,  # 默认是False
    )
    # 定义请求地址传入的参数
    res=alipay.direct_pay(
        subject=models.Order.objects.last().pname,  # 商品描述
        out_trade_no=models.Order.objects.last().oid,  # 订单号
        total_amount=models.Order.objects.last().take,  # 交易金额(单位是元，保留两位小数)
    )
    #生成跳转到支付宝支付页面的url
    url='https://openapi.alipaydev.com/gateway.do?{0}'.format(res)
    return redirect(url)
 
 
 
 
 
 
def show(request):
    if request.method == 'GET':
        alipay = AliPay(
            appid="2021000119681986",  
            app_notify_url='http://127.0.0.1:5600/app01/check/',
            return_url='http://127.0.0.1:5600/app01/show/',
            app_private_key_path=r'D:\Django-water\water\app01\rsakey\private2048.txt',  # 应用私钥
            alipay_public_key_path=r'D:\Django-water\water\app01\rsakey\paypublic.txt',  # 支付宝公钥
            debug=True,  # 默认是False
        )
        param=request.GET.dict()  # 获取请求携带的参数并转换成字典类型
        sign=param.pop('sign', None)  # 获取sign的值
        # 对sign参数进行验证
        statu = alipay.verify(param,sign)
        if statu:
            return render(request, 'show.html', {'msg': '支付成功'})
        else:
            return render(request, 'show.html', {'msg': '支付失败'})
    else:
        return render(request, 'show.html', {'msg': '只支持GET请求，不支持其它请求'})
 
 
def check(request):
    if request.method=='POST':
        alipay=AliPay(appid="22021000119681986",
            app_notify_url='http://127.0.0.1:5600/app01/check/',  # 支付宝会向这个地址发送post请求
            return_url='http://127.0.0.1:5600/show_msg/',  # 支付宝会向这个地址发送get请求
            app_private_key_path=r'D:\Django-water\water\app01\rsakey\private2048.txt',  # 应用私钥
            alipay_public_key_path=r'D:\Django-water\water\app01\rsakey\paypublic.txt',  # 支付宝公钥
            debug=True,
        )
        body=request.body.decode('utf-8')  # 转成字符串
        post_data = parse_qs(body)  # 根据&符号分割
        post_dict = {}
        for k, v in post_data.items():
            post_dict[k] = v[0]
        sign = post_dict.pop('sign', None)
        status = alipay.verify(post_dict, sign)
        if status:  # 支付成功
            return HttpResponse('支付成功')
        else:
            return HttpResponse('支付失败')
    else:
        return HttpResponse('只支持POST请求')

def index1(request):
    return render(request,'index1.html')

def admin(request):
    return render(request,'admin.html')
class LoginModelForm(BootStrapModelForm):
    username=forms.CharField(
        label="用户名",
        widget=forms.TextInput,
        required=True,
    )
    password=forms.CharField(
        label="密码",
        widget=forms.PasswordInput,
        required=True
    )
    code = forms.CharField(
        label="验证码",
        widget=forms.TextInput,
        required=True,
    )
    class Meta:
        model=models.Role
        fields="__all__"
    def clean_password(self):
        pwd=self.cleaned_data["password"]
        return md5(pwd)
def login(request):
    if request.method=="GET":
        form=LoginModelForm()
        return render(request,'login.html',{"form":form})
    form=LoginModelForm(data=request.POST)
    if form.is_valid():
       
        password=form.cleaned_data["password"]
        username=form.cleaned_data["username"]
       
        user_input_code = form.cleaned_data.pop('code')
        code = request.session.get('image_code', "")
        if code.upper() != user_input_code.upper():
            print('hello')
            form.add_error("code", "验证码错误")
            print('jfiej')
            return render(request, 'login.html', {"form": form})

        role=int(request.POST.get("role"))
        print(role)
        if role==1:
            object=models.Admin.objects.filter(aname=username,password=password).first()

            if not object:
                form.add_error("password","用户名或密码错误")
            
                return render(request,'login.html',{'form':form})
            request.session["info"]={'id':object.id,'name':object.aname}
           
            return redirect("/admin/")
        if role==2:
            object=models.Water_workers.objects.filter(wname=username,password=password).first()
            print(object)
            if not object:
                form.add_error("password","用户名或密码错误")

                return render(request,'login.html',{'form':form})
            request.session["info"]={'id':object.id,'name':object.wname}
            return redirect("/worker/")
    return render(request,'login.html',{'form':form})

def image_code(request):
    """生成图片"""
    # 调用pillow函数，生成图片
    img, code_string = check_code()

    # 写入到自己的session中(一边后续获取验证码再进行校验)
    request.session["image_code"] = code_string
    # 给Session设置60s超时
    request.session.set_expiry(60)

    stream = BytesIO()
    img.save(stream, 'png')
    return HttpResponse(stream.getvalue())

def logout(request):
    request.session.clear()
    return redirect('/login/')





